import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getFavorites, createFavorites, deleteFavorites, updateFavorite, reqGetFavorites } from './favorites.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户 ID
  const { user_id } = request.body;
  const { type } = request.body;
  const pageNo = parseInt(`${request.body.pageNo}`, 10);
  const pageSize = parseInt(`${request.body.pageSize}`, 10);

  const data = await getFavorites(user_id, type, pageNo, pageSize);
  response.send(data);;
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  const likeCon = request.body;
  // let user_id = request.user.id;
  // likeCon.user_id = user_id;
  let user_id = request.body.user_id;
  let book_id = request.body.book_id;

  // 创建
  try {

    let userFavorites = await reqGetFavorites(parseInt(user_id, 10), parseInt(book_id, 10));
    
    if (userFavorites[0] && [userFavorites as any].length > 0 && userFavorites[0].id > 0) {
      let postId = userFavorites[0].id;
      await deleteFavorites(parseInt(postId, 10)); // 取消收藏

      return response.send({
        code: 200,
        message: 'ئۆچۈرۈش مۇۋەپىقىيەتلىك بولدى !'
      })
    } else {
      await createFavorites(likeCon); // 添加收藏
      // response.send(data);

      return response.send({
        code: 201,
        message: 'ساقلاش مۇۋەپىقىيەتلىك بولدى !'
      })
    }
  } catch (error) {
    next(error);
  }
}

/**
 * 创建预览和收藏内容
 */
export const preview = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  const type = parseInt(`${request.body.type}`, 10);
  const user_id = parseInt(`${request.body.user_id}`, 10);

  // 创建
  try {
    await getFavorites(user_id, type, 1, 10);
    
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除
  try {
    const data = await deleteFavorites(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}
